package org.yuanqiframework.yuanqi.web.auth.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.yuanqiframework.yuanqi.core.utils.StringUtils;
import org.yuanqiframework.yuanqi.web.auth.AuthContext;
import org.yuanqiframework.yuanqi.web.auth.entity.LoginDTO;
import org.yuanqiframework.yuanqi.web.auth.service.TokenService;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器 验证token有效性,面向系统用户
 *
 * @author 曹波涛
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        //从redis获取
        LoginDTO loginDTO = tokenService.getLoginDTO(request);
        if (StringUtils.isNotNull(loginDTO)) {
            //验证令牌有效期
            tokenService.verifyToken(loginDTO);
            AuthContext authContext = new AuthContext(loginDTO);
        } else {
            //匿名用户
            AuthContext authContext = new AuthContext(null);
        }
        chain.doFilter(request, response);
    }
}